package com.example.yyy

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Bundle
import android.text.Layout
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import org.jetbrains.anko.selector
import org.jetbrains.anko.toast

class DyFragment: Fragment() {

    private var ctx:Context? = null
    private var mPosition:Int = 0
    private var mImageId:Int = 0
    private var mDesc:String? = null
    private var mPrice:Int = 0

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        ctx = activity
        //碎片内部通过argument获取外部输入参数
        if (arguments!=null){
            mPosition = arguments!!.getInt("position",0)
            mImageId = arguments!!.getInt("image_id",0)
            mDesc = arguments!!.getString("desc")
            ctx?.toast(mDesc+"")
            mPrice= arguments!!.getInt("price",0)
        }
        val view = inflater.inflate(R.layout.layout_dy, container, false)
        //Fragment内部任需要findViewById获得控件对象
        val img_dy_po = view.findViewById<ImageView>(R.id.img_dy_po)
        val colorSet = view.findViewById<LinearLayout>(R.id.ll_dy_colorSet)
        val tv_dy_price = view.findViewById<TextView>(R.id.tv_dy_price)
        val tv_dy_desc = view.findViewById<TextView>(R.id.tv_dy_desc)

        img_dy_po.setImageResource(mImageId)
        tv_dy_price.text = "价格：$mPrice 元"
        tv_dy_desc.text = "描述：$mDesc"

        img_dy_po.setOnClickListener{
            val stringArray:List<String> = ctx!!.resources.getStringArray(R.array.colorName).toList()
            //anko库选择弹窗
            ctx?.selector("选择背景色",stringArray){ ds, i ->
                val colorString = ctx!!.resources.getStringArray(R.array.colorId).toList()[i]
                colorSet.setBackgroundColor(Color.parseColor(colorString))
                //设置广播意图名称为EVENT
                val intent = Intent(EVENT)
                intent.putExtra("color",colorString)
                //发送背景色变更广播
                ctx?.sendBroadcast(intent)
            }
        }

        return view
    }

    companion object{
        const val EVENT = "com.example.yyy.DyFragment"
        //利用伴生对象获取碎片实例的静态方法
        fun newInstance(position:Int,image_id:Int,desc:String,price:Int):DyFragment{
            val dyFragment = DyFragment()

            val bundle = Bundle()
            bundle.putInt("position",position)
            bundle.putInt("image_id",image_id)
            bundle.putString("desc",desc)
            bundle.putInt("price",price)

            dyFragment.arguments = bundle

            return dyFragment
        }
    }
}
